<?php

namespace App\Http\Controllers;

use App\Exceptions\BaseException;
use App\Http\Requests\CanteenRequest;
use App\Services\Canteen;
use Illuminate\Http\Request;


class CanteenController extends Controller
{
    protected $canteenService;

    function __construct()
    {
        parent::__construct();
        $this->canteenService = new Canteen();
    }

    /**
     * 餐厅列表
     *
     * @param Request $request
     * @return array
     */
    public function index(Request $request)
    {
        try{
            $limit = intval($request->get('count', 20));
            $canteens = $this->canteenService->getList($limit);
            return $this->success('',$canteens);
        }catch(BaseException $e){
            return $this->fail($e->getMessage());
        }catch (\Exception $e){
            \Log::error($e);
            return $this->fail('发生意外错误, 请稍后重试!');
        }
    }

    /**
     * 获取单个餐厅信息
     *
     * @param $id
     * @return array
     */
    public function show($id)
    {
        try{
            $id = intval($id);
            $user = $this->canteenService->show($id);
            return $this->success('', $user);
        }catch(BaseException $e){
            return $this->fail($e->getMessage());
        }catch (\Exception $e){
            \Log::error($e);
            return $this->fail('发生意外错误, 请稍后重试!');
        }
    }

    /**
     * 新增餐厅
     *
     * @param CanteenRequest $request
     * @return array
     */
    public function store(CanteenRequest $request)
    {
        try{
            $name = trim($request->get('name'));
            $address = trim($request->get('address'));
            $user_id = intval($request->get('user_id'));
            $this->canteenService->create(compact('name', 'address', 'user_id'));
            return $this->success('新增餐厅成功!');

        }catch(BaseException $e){
            return $this->fail($e->getMessage());
        }catch (\Exception $e){
            \Log::error($e);
            return $this->fail('发生意外错误, 请稍后重试!');
        }
    }

    /**
     * 更新餐厅信息
     *
     * @param CanteenRequest $request
     * @param $id
     * @return array
     */
    public function update(CanteenRequest $request, $id)
    {
        try{
            $id = intval($id);
            $name = trim($request->get('name'));
            $address = trim($request->get('address'));
            $user_id = intval($request->get('user_id'));
            $this->canteenService->update($id, compact('name', 'address', 'user_id'));
            return $this->success('餐厅已更新!');
        }catch(BaseException $e){
            return $this->fail($e->getMessage());
        }catch (\Exception $e){
            \Log::error($e);
            return $this->fail('发生意外错误, 请稍后重试!');
        }
    }

}
